package com.smartrm.trade.domain.service;

import com.smartrm.globalinfrcore.annoation.DomainService;
import com.smartrm.globalinfrcore.api.CommonError;
import com.smartrm.globalinfrcore.exception.DomainException;
import com.smartrm.trade.domain.OrderDO;
import com.smartrm.trade.domain.SlotVendingMachineDO;
import com.smartrm.trade.domain.remote.TradeDeviceService;
import com.smartrm.trade.domain.repository.VendingMachineRepository;
import com.smartrm.trade.domain.valueobject.StockedCommodityVOJ;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.math.BigDecimal;

/*
 * @program: common-starters
 * @description: 活动领域服务 1: 公共的业务，2：模糊的业务 3：实体之间的合作使用
 * 4:聚合之间的协作采用领域事件
 * 都可以放在领域服务里面
 * @author: houhong
 * @create: 2023-01-11 01:58
 */
@DomainService
public class ActivityService {

    private static final Logger logger = LoggerFactory.getLogger(ActivityService.class);

    public BigDecimal caculateOrderAmount(OrderDO order) {
        // caculate order amount with activity
        return BigDecimal.ZERO;
    }

    @Autowired
    @Qualifier("tradeVendingMachineRepository")
    private VendingMachineRepository vendingMachineRepository;

    /*
     * 货道售卖机完成订单
     */
    public void vendingMachineFinishOrder(long machineId, long orderId, TradeDeviceService deviceService) throws Exception {

        SlotVendingMachineDO slotVendingMachineDO = vendingMachineRepository.getSlotVendingMachineById(machineId);

        if (slotVendingMachineDO.curOrder == null || slotVendingMachineDO.curOrder.getOrderId() != orderId) {
            logger.warn("order finished when slot vending machine has release it:{},{}", machineId,
                    orderId);
            return;
        }
        OrderDO curOrder = slotVendingMachineDO.curOrder;
        //弹出商品
        if (curOrder.getCommodities().size() > 1) {
            throw new DomainException(CommonError.UnExpected)
                    .withMsg("slot vending machine only support one commodity order");
        }
        for (StockedCommodityVOJ commodity : curOrder.getCommodities()) {
            deviceService.popCommodity(machineId, commodity.getCommodityId(), orderId);
        }
        //协作,调用订单实体完成
        slotVendingMachineDO.curOrder.successed();
    }

}